document.observe("dom:loaded", function(e) {    
  
    new Ajax.Request('/app/cars', {
        method:'GET',
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON();
            var jdata = '<option>--select car for which gas was purchased--';
            for (var j = 0; j < json.length; j++) {
                jdata += '<option value=' + json[j].cid + '>' + json[j].carname + "</option>";
            }
            $('car-list').update(jdata);
        },
        onFailure: function(transport){
            $('car-list').update('<option>Can not get data from server!</option>');
        }
    });
 
    new Ajax.Request('/app/vendors', {
        method:'GET',
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON();
            var jdata = '<option>--select vendor--';
            for (var j = 0; j < json.length; j++) {
                jdata += '<option value=' + json[j].vid + '>' + json[j].vendorname + "</option>";
            }
            $('vendor-list').update(jdata);
        },
        onFailure: function(transport){
            $('vendor-list').update('<option>Can not get data from server!</option>');
        }
    });

    // listen to the submit purchase request to be clicked - submit via AJAX
    // update the value of status div
    $('submit-gas-purchase-button').observe('click', function(e) {
        // alert('clicked!');
        $('submit-gas-purchase').request({
            method: 'post',
            onComplete: function(response) { 
                $('submit-status').update(response.responseText);     
                // update last 10 records by car
                var form = $('submit-gas-purchase');
                var carid = form['carid'];
                var url = '/app/cars/gas?carid=' + $(carid).getValue() + '&sort=desc&rows=10'; 
                new Ajax.Request(url, {
                    method: 'get',
                    onSuccess: function(response) {   
                        var json = response.responseText.evalJSON();
                        var jdata = '<table>';
                        jdata += '<tr><th>car</th><th>odometer</th><th>bill (US$)</th><th>miles traveled</th><th>gallons</th></tr>';
                        for (var j = 0; j < json.length; j++) {
                            jdata += '<tr><td>' + json[j].car + '</td><td>' + json[j].odometer + '</td><td>' + json[j].bill + '</td><td>' + json[j].milesTraveled + '</td><td>' + json[j].gallons + '</td></tr>';
                        }   
                        jdata += '</table>';
                        $('last-ten-records-by-car').update(jdata);
                    },
                    onFailure: function(response) {
                        $('last-ten-records-by-car').update(response.responseText);
                    }
                });
            } 
        });
        
    }); 
});
